import java.util.HashSet;
import java.util.Set;

/**
 * @author LKQ
 * @date 2021/12/23 22:04
 * @description 散列表 + 滑动窗口
 */
public class FormalSolution {
    public static void main(String[] args) {
        FormalSolution solution = new FormalSolution();
        int[] nums = {1, 2, 2, 1, 2, 3};
        System.out.println(solution.containsNearbyDuplicate(nums, 2));
    }

    public boolean containsNearbyDuplicate(int[] nums, int k) {
        // 散列表能够高效的查询和删除元素，当k较大时具有优势
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i < nums.length; ++i) {
            if (!set.add(nums[i]))  {
                return true;
            }
            if (set.size() > k) {
                set.remove(nums[i - k]);
            }
        }
        return false;
    }
}
